import Vue from 'vue'
import Vuex from 'vuex'
//导入持久化依赖包
import VuexPersistence from 'vuex-persist'
//实例化持久化插件对象
const vuexLocal = new VuexPersistence({
  storage: window.sessionStorage,//存储介质,
  key: "vuex",//存储到本地存储
})
Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    history: [], // 存储历史记录
    token: '', //判断登陆
    users:{},
    cart:[],
  },
  mutations: {
    // 历史记录
    history(state, keyword) {
      if (state.history.length >= 10) {
        state.history.pop()
      }
      state.history.unshift(keyword);
    },
    // 清空历史记录
    del(state) {
      state.history = []
    },
    // 登录
    login(state, data) {
      // console.log(data)
      state.token = data.token;
      state.users = data;
    },
    // 退出
    logout(state){
      state.token = '';
      state.users = {};
    },
    // 添加到购物车
    add(state,obj){
      var index = state.cart.findIndex((item)=>{
        return item.id == obj.id;
      })
      console.log(index)
      if(index > -1){
        state.cart[index].num += obj.num;
      }else{
        state.cart.push(obj);
      }
      
    }
  },
  getters:{
    // 统计购物车商品的数量
    nums(state){
      let num = 0;
      state.cart.forEach(item=>{
        if(item.checked == true){
          num += item.num;
        }
      })
      return num;
    },
    // 计算总价格
    total(state){
      return state.cart.reduce((pre,cur)=>{
        if(cur.checked == true){
          pre += cur.num * cur.price;
        }
        return pre;
      },0)
    }
  },
  actions: {
  },
  modules: {
  },
  plugins: [vuexLocal.plugin]
})
